app.service('RecordService', function($rootScope, $http, $q){
    var url = $rootScope.api.record;
    var data = {
        page : 1,
        limit : 10,
        items : [],
    };
    this.items = data.items;
    this.load = function(backmethod){
        var promise = this.getList(data.page, data.limit, backmethod);

        promise.then(function(d){
            angular.forEach(d, function(item){
                data.items.push(item);
            });
            data.page++;
        }, function(res){
            if(res && res.message){
                console.log(res.message);
            }
        });

    };
    this.getList = function(page, limit, backmethod){
        var deferred = $q.defer();
        var promise = deferred.promise;

        $http.get(url, {params : {page : page, limit : limit}})

            .success(function(res){

                deferred.resolve(res.data);
                data.page++;

                if(backmethod){
                    backmethod(res.data.length < data.limit);
                }
                // console.log(data.items);
            })
            .error(function(res){
                deferred.reject(res);
            });

        return promise;
    }
    this.post = function(item){
        var record = {};
        var promise = $http.post(url, {data : item}).success(function(res){
            console.log(res);
        });
        promise.then(function(res){
            record = res.data;
        }, function(err){
            console.log(err);
        });
        return record;

    };
    this.get = function(id){
        $http.get(url + '/' + id).success(function(res){
            console.log(res);
        });
    };
    this.put = function(item){
        $http.put(url + '/' + id, {data : item}).success(function(res){
            console.log(res);
        });
    };
    this.delete = function(id){
        $http.delete(url + '/' + id).success(function(res){
            console.log(res);
        });
    }
});
